package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.PageResult;
import com.woniu.mapper.PatrolMapper;
import com.woniu.pojo.Order;
import com.woniu.pojo.Patrol;
import com.woniu.service.IPatrolServices;
import com.woniu.vo.*;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PatrolServicesImpl extends ServiceImpl<PatrolMapper, Patrol> implements IPatrolServices {
    @Resource
    private PatrolMapper patrolMapper;

    @Override
    /**
     * 查巡检员通过id，但是要返回一个集合的那种
     * */
    public List searchPatrolById(Long id) {
        Patrol patrol = patrolMapper.selectById(id);
        if(patrol == null){
            return null;
        }
        PatrolReturnVo patrolReturnVo = new PatrolReturnVo();
        BeanUtils.copyProperties(patrol,patrolReturnVo);
        patrolReturnVo.setWorkTime(patrol.getStartTime()+"-"+patrol.getEndTime());
        List<String> streetNames =  patrolMapper.selectStreetNameByPatrolId(id);
        if(streetNames.size() < 1){
            patrolReturnVo.setStreet("暂无管辖");
        }else {
            String street ="";
            for (String streetName : streetNames) {
                street = street + streetName+",";
            }
            patrolReturnVo.setStreet(street);
        }
        List<PatrolReturnVo> list = new ArrayList<>();
        list.add(patrolReturnVo);
        return list;
    }

    @Override
    /**
    * 查订单的完成率，订单相关的数据
    * */
    public List searchOrderById(Long id) {
        //先去查完成的订单，所有的订单，和异常的订单
        int all = patrolMapper.selectOrderAllById(id);
        int success = patrolMapper.selectOrderSuccessById(id);
        int unusual = patrolMapper.selectOrderUnusualById(id);
        OrderSearchReturnByPatrolIdVo patrolIdVo = new OrderSearchReturnByPatrolIdVo();
        //吧查到的数据组装到vo里
        patrolIdVo.setAllOrder(all);
        patrolIdVo.setSuccessOrder(success);
        patrolIdVo.setUnusualOrder(unusual);
        //以为完成率是个BigDecimal，所以要计算一下
        BigDecimal successOrder = new BigDecimal(success);
        BigDecimal allOrder = new BigDecimal(all);
        //防止这小子没有完成订单，直接出给我报错
        if(all == 0){
            patrolIdVo.setSuccessPen("0");
        }else {
            //这个地方，BigDecimal计算要带上保留的几位小鼠和余数的处理方式
            BigDecimal orderSusses = successOrder.divide(allOrder,2,BigDecimal.ROUND_UP);
            BigDecimal multiply = orderSusses.multiply(new BigDecimal(100));
            patrolIdVo.setSuccessPen(multiply.toString()+"%");
        }
        List<OrderSearchReturnByPatrolIdVo> list = new ArrayList<>();
        list.add(patrolIdVo);
        return list;
    }

    @Override
    /**
     * 查所有的订单表
     * */
    public PageResult searchOrderListById(Long id,Integer currentPage, Integer pageSize, OrderPatrolSearchVo orderPatrolSearchVo) {
        //我根据巡检员id去查到了订单集合
        //先校验一下参数
        if(currentPage == null || currentPage < 1){
            currentPage = 1;
        }
        if(pageSize == null || pageSize < 1 || pageSize > 5 ){
            pageSize = 5;
        }
        Page<Patrol> page = new Page<>(currentPage,pageSize);
        Page<Order> orderList = patrolMapper.selectOrderByPatrolId(page,id,orderPatrolSearchVo);
        //但是这个集合不是我要的集合
        //所以我new一个我要的集合
        List<OrderSearchReturnByOrderIdVo> list = new ArrayList<>();
        for (Order order : orderList.getRecords()) {
            OrderSearchReturnByOrderIdVo orderIdVo = new OrderSearchReturnByOrderIdVo();
            BeanUtils.copyProperties(order,orderIdVo);
            //我要的数据，它很多都没有直接的，所以我只能自己去查，再封装
            String street = patrolMapper.selectStreetNameBySpaceId(order.getSpaceId());
            orderIdVo.setStreet(street);
            String carNum =  patrolMapper.selectCarNumByCarId(order.getCarId());
            orderIdVo.setCarNum(carNum);
            list.add(orderIdVo);
        }
        return new PageResult(orderList.getTotal(),list);
    }

    @Override
    /**
     *
     * 查考勤列表
     * */
    public PageResult searchCheckList(Long id, Integer currentPage, Integer pageSize) throws ParseException {
            Page<CheckResVo> page = new Page<>(currentPage,pageSize);
            Page<CheckResVo> checkResVoPage = patrolMapper.selectCheck(page,id);
            //我拿到所有的考勤记录了，
            //组装一下
            List<CheckListResVo> list = new ArrayList<>();
        for (CheckResVo record : checkResVoPage.getRecords()) {
            CheckListResVo checkListResVo = new CheckListResVo();
            Date createTime = record.getCreateTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format(createTime);
            String[] strings = dateStr.split(" ");
            checkListResVo.setCheckDate(strings[0]);
            checkListResVo.setCheckTime(strings[1]);
            //状态这里需要一个比较器。
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            //吧拿到的打卡时间转换成日期格式
            Date parse = dateFormat.parse(strings[1]);
            //设置一个打卡时间
            Date parse1 = dateFormat.parse("12:00:00");
            if(parse.before(parse1)){
                //如果在打卡时间前打卡就是正常打卡
                checkListResVo.setCheckStatus("0");
            }else {
                //否则就是迟到
                checkListResVo.setCheckStatus("1");
            }
            list.add(checkListResVo);
        }
        return new PageResult(checkResVoPage.getTotal(),list);
    }

    @Override
    /**
     * 查订单详情
     * */
    public OrderDetailResVo searchOrderDetail(Long id) {
        //拿到的是订单的id
        Order order = patrolMapper.selectOrderById(id);
        //拿到订单了
        OrderDetailResVo orderDetailResVo = new OrderDetailResVo();
        BeanUtils.copyProperties(order,orderDetailResVo);
        Date createTime = order.getCreateTime();
        Date leaveTime = order.getLeaveTime();
        long startTime = createTime.getTime();
        long endTime = leaveTime.getTime();
        //这里是分钟，但是不太合理，
        //这个是分钟
        Long parkingTime = (endTime-startTime)/1000/60;
        //我看看你听了多少天
        Long day =  parkingTime/60/24;
        //听了几个小时
        Long hour = (parkingTime-day*24*60)/60;
        //听了几分钟
        Long mm = (parkingTime-day*24*60-hour*60);
        orderDetailResVo.setParkingTime(day +"天"+hour+"小时"+mm+"分");

        //拿到车牌
        String num = patrolMapper.selectCarNumByCarId(order.getCarId());
        orderDetailResVo.setNum(num);
        //拿到用户名
        String userName = patrolMapper.selectUserNameByCarId(order.getCarId());
        orderDetailResVo.setUserName(userName);
        //拿到路段名
        String street = patrolMapper.selectStreetNameBySpaceId(order.getSpaceId());
        orderDetailResVo.setRoadName(street);
        //拿到地磁编号
        Long magnetId =  patrolMapper.selectMagnetId(order.getSpaceId());
        orderDetailResVo.setMagnetId(magnetId);
        //拿到巡检人员
        Patrol patrol = patrolMapper.selectById(order.getPatrolId());
        orderDetailResVo.setPatrolName(patrol.getName());
        //通过订单号去那到图片的集合
        List<String> stringList = patrolMapper.selectImageByOrderId(order.getId());
        orderDetailResVo.setOrderImageList(stringList);
        return orderDetailResVo;
    }

    @Override
    /**
     * 查收费模式
     * */
    public List searchChargeRuleByRoadId(Long id) {
        //我要根据这个路段id去查收费标准，一条路有4个收费模式
        Long roadId = patrolMapper.selectRoadIdByOrderId(id);
        List<ChargeReturnVo> voList = patrolMapper.selectChargeRulByRoadId(roadId);
        return voList;
    }

    /**
     * 登录
     * @param loginVo 登录传入的参数 手机号、密码
     * @return 返回登录的巡检员
     */
    @Override
    public Patrol login(PatrolLoginVo loginVo) {
        QueryWrapper<Patrol> loginWrapper = new QueryWrapper<>();
        loginWrapper.eq("phone", loginVo.getPhone());
        loginWrapper.eq("password", loginVo.getPassword());
        return getOne(loginWrapper);
    }

    @Override
    /**
     * 分页条件查，三个参数
     * */
    public PageResult searchByPage(Integer currentPage, Integer pageSize, PatrolSearchVo patrolSearchVo) {
        //先校验一下参数
        if(currentPage == null || currentPage < 1){
            currentPage = 1;
        }
        if(pageSize == null || pageSize < 1 || pageSize > 5 ){
            pageSize = 5;
        }
        Page<Patrol> page = new Page<>(currentPage,pageSize);
        IPage<Patrol> patrolIPage = null;
        if(patrolSearchVo.getStreetId() == null && patrolSearchVo.getName() == null && patrolSearchVo.getPhone() == null){
            patrolIPage = patrolMapper.selectPage(page,null);
        }else {
            patrolIPage = patrolMapper.selectPages(page,patrolSearchVo);
        }
        //查出来的是巡检员对象，不是我要传回去的对象，组装一下
        List<PatrolReturnVo> patrolReturnVoList = new ArrayList<>();
        for (Patrol patrol : patrolIPage.getRecords()) {
            //拿到每一个巡检员对象，我要根据它的id去查我要的信息
            PatrolReturnVo patrolReturnVo = new PatrolReturnVo();
            BeanUtils.copyProperties(patrol,patrolReturnVo);
            List<String> streetNames =  patrolMapper.selectStreetNameByPatrolId(patrol.getId());
            if(streetNames.size() < 1){
                patrolReturnVo.setStreet("暂无管辖");
            }else {
                String street ="";
                for (String streetName : streetNames) {
                    street = street + streetName+",";
                }
                patrolReturnVo.setStreet(street);
            }
            //还有一个订单完成率没差
            int successOrder = patrolMapper.selectOrderSuccessById(patrol.getId());
            int allOrder = patrolMapper.selectOrderAllById(patrol.getId());
            BigDecimal success = new BigDecimal(successOrder);
            BigDecimal all = new BigDecimal(allOrder);
            if(allOrder == 0){
                patrolReturnVo.setOrderSusses("0");
            }else {
                BigDecimal orderSusses = success.divide(all,2,BigDecimal.ROUND_UP);
                BigDecimal multiply = orderSusses.multiply(new BigDecimal(100));
                patrolReturnVo.setOrderSusses(multiply.toString()+"%");
            }
            //封装一下执勤时间
            String startTime = patrol.getStartTime();
            String endTime = patrol.getEndTime();
            String workTime = startTime+"-"+endTime;
            patrolReturnVo.setWorkTime(workTime);
            patrolReturnVoList.add(patrolReturnVo);
        }
        return new PageResult(patrolIPage.getTotal(),patrolReturnVoList);
    }

    @Override
    /**
     * 删除的方法
     * */
    public Boolean removeByPatrolId(Long id) {
        //我拿到了巡检员的id，那么我要去吧巡检员删掉，还要吧巡检员路段中间表删掉，还要把订单？
        int i = patrolMapper.deleteById(id);
        patrolMapper.deleteRelationById(id);
        return i > 0 ? true : false;
    }

    @Override
    /**
     * 新增的方法
     * */
    public Boolean add(PatrolAddVo patrolAddVo) {
        //非空校验
        String name = patrolAddVo.getName();
        if(name == null || name.length() < 1){
            return  false;
        }
        String endTime = patrolAddVo.getEndTime();
        if(endTime == null || endTime.length() < 1){
            return false;
        }
        String password = patrolAddVo.getPassword();
        if(password == null || password.length() < 1){
            return false;
        }
        String phone = patrolAddVo.getPhone();
        if(phone.length() < 10 || phone.length() > 11 ){
            return false;
        }
        String status = patrolAddVo.getStatus();
        if(status == null || status.length() < 1){
            return false;
        }
        String startTime = patrolAddVo.getStartTime();
        if(startTime == null || startTime.length() < 1){
            return false;
        }
        List<Long> street = patrolAddVo.getStreet();
        //我拿到的是个vo，所以要拆分一下
        Patrol patrol = new Patrol();
        BeanUtils.copyProperties(patrolAddVo,patrol);
        patrol.setCreateTime(new Date());
        patrol.setIsDeleted("0");
        patrol.setUpdateTime(new Date());
        int insert = patrolMapper.insert(patrol);
        for (Long streetId : street) {
            RlRoadPatrolAddVo rlRoadPatrolAddVo = new RlRoadPatrolAddVo();
              rlRoadPatrolAddVo.setPatrolId(patrol.getId());
              rlRoadPatrolAddVo.setRoadId(streetId);
              rlRoadPatrolAddVo.setCreateTime(new Date());
              rlRoadPatrolAddVo.setUpdateTime(new Date());
              patrolMapper.insertRelation(rlRoadPatrolAddVo);
        }
        return insert > 0 ? true : false;
    }

    @Override
    /**
     * 根据id查
     * */
    public PatrolAddVo searchById(Long id) {
        Patrol patrol = patrolMapper.selectById(id);
        PatrolAddVo patrolAddVo = new PatrolAddVo();
        BeanUtils.copyProperties(patrol,patrolAddVo);
        List<Long> longList =  patrolMapper.selectStreetIdByPatrolId(id);
        patrolAddVo.setStreet(longList);
        return patrolAddVo;
    }

    @Override
    /**
     * 修改
     * */
    public Boolean modify(PatrolAddVo patrolAddVo) {
        //非空校验
        //修改不应该改密码
        String name = patrolAddVo.getName();
        if(name == null || name.length() < 1){
            return  false;
        }
        String endTime = patrolAddVo.getEndTime();
        if(endTime == null || endTime.length() < 1){
            return false;
        }
        String phone = patrolAddVo.getPhone();
        if(phone.length() < 10 || phone.length() > 11 ){
            return false;
        }
        String status = patrolAddVo.getStatus();
        if(status == null || status.length() < 1){
            return false;
        }
        String startTime = patrolAddVo.getStartTime();
        if(startTime == null || startTime.length() < 1){
            return false;
        }
        Patrol patrol = new Patrol();
        BeanUtils.copyProperties(patrolAddVo,patrol);
        int i = patrolMapper.updateById(patrol);
        //吧中间表干掉
        patrolMapper.deleteRelationById(patrolAddVo.getId());
        //重新组装
        List<Long> street = patrolAddVo.getStreet();
        for (Long streetId : street) {
            RlRoadPatrolAddVo rlRoadPatrolAddVo = new RlRoadPatrolAddVo();
            rlRoadPatrolAddVo.setPatrolId(patrol.getId());
            rlRoadPatrolAddVo.setRoadId(streetId);
            rlRoadPatrolAddVo.setCreateTime(new Date());
            rlRoadPatrolAddVo.setUpdateTime(new Date());
            //重新添加
            patrolMapper.insertRelation(rlRoadPatrolAddVo);
        }
        return i > 0 ?true:false;
    }

    @Override
    public Boolean stopPatrol(Long id) {
        int i = patrolMapper.updateStatusToStopById(id);
        return i > 0 ? true : false ;
    }

    @Override
    public Boolean usePatrol(Long id) {
        int i = patrolMapper.updateStatusToUseById(id);
        return i > 0 ? true : false ;
    }
}
